<template>
  <!-- 配送订单 -->
  <div class="takeout-order">
    <Return />
    <div class="takeout-order-header" :style="{ paddingTop: capsuleTop + 'px' }">
      <div class="takeout-order-header-top">
        <div class="takeout-order-header-top-left takeout-order-header-top-item">
          <div>今日收入</div>
          <div class="priceStr">
            <div>￥</div>
            <div>{{ todayIncome.toFixed(2) }}</div>
          </div>
        </div>
        <div class="takeout-order-header-top-right takeout-order-header-top-item">
          <div class="top-title">
            <div>累计收入</div>
            <div @click="handleWithdraw">提现</div>
          </div>
          <div class="priceStr">
            <div>￥</div>
            <div>{{ totalIncome.toFixed(2) }}</div>
          </div>
        </div>
      </div>
      <div class="takeout-order-header-bottom">
        <template v-for="(item, index) in takeoutOrderList" :key="item.title">
          <div class="takeout-order-header-bottom-item">
            <div class="item-box" :class="{ 'item-box-active': index === activeIndex }" @click="handleTabChange(index)">
              <div>{{ item.title }}</div>
            </div>
          </div>
        </template>
      </div>
    </div>

    <scroll-view class="takeout-order-content" scroll-y="true" :style="{ height: contentHeight + 'px' }"
      @scrolltolower="loadMore" refresher-enabled="true" :refresher-triggered="refreshing"
      @refresherrefresh="onRefresh">
      <!-- 加载状态 -->
      <div v-if="loading && orderList.length === 0" class="loading-container">
        <div class="loading">加载中...</div>
      </div>

      <!-- 空状态 -->
      <div v-else-if="!loading && orderList.length === 0" class="empty-container">
        <div class="empty-text">暂无订单</div>
      </div>

      <!-- 订单列表 -->
      <template v-else>
        <div v-for="(order, index) in orderList" :key="order.id" class="takeout-order-content-item"
          @click="viewOrderDetail(order)">
          <div class="takeout-order-content-item-header">
            <img :src="order.storeAvatar || '../static/imgs/banner.png'" alt="">
            <div class="takeout-order-content-item-header-title">
              <div class="takeout-order-content-item-header-title-top">
                <span class="store-name">{{ order.storeName }}</span>
                <span class="store-name-tag">{{ getStatusText(order.status) }}</span>
              </div>
              <div class="takeout-order-content-item-header-title-button">
                <span>订单号：{{ order.orderNo }}</span>
              </div>
            </div>
          </div>
          <div class="page-line"> </div>
          <div class="item-center">
            <template v-for="(item, itemIndex) in order.items" :key="itemIndex">
              <div class="info">
                <img :src="item.image || '../static/imgs/banner.png'" alt="">
                <div class="info-content">
                  <div class="info-content-top">
                    <span class="store-name">{{ item.name }}</span>
                    <span class="store-name-tag">
                      <i>实付</i> <i>¥</i> <i>{{ item.priceStr.toFixed(2) }}</i>
                    </span>
                  </div>
                  <div class="info-content-button" v-if="item.remark">
                    <div class="info-content-button-item-remark">
                      <div>{{ item.remark }}</div>
                    </div>
                  </div>
                  <div class="info-content-button">
                    <div class="info-content-button-item">
                      <div>x</div>
                      <div>{{ item.quantity }}</div>
                    </div>
                  </div>
                </div>
              </div>
            </template>
          </div>
          <div class="total-priceStr">
            <div>共计</div>
            <div>¥</div>
            <div>{{ order.totalAmountStr.toFixed(2) }}</div>
          </div>
          <div class="page-line"> </div>
          <div class="takeout-order-content-item-footer">
            <div class="footer-item" v-if="order.remark">
              <div class="footer-item-left">备注</div>
              <div class="footer-item-right">{{ order.remark }}</div>
            </div>
            <div class="footer-item">
              <div class="footer-item-left">收货地址</div>
              <div class="footer-item-right">{{ order.deliveryAddress }}</div>
            </div>
            <div class="footer-item" v-if="order.distributionName">
              <div class="footer-item-left">骑手</div>
              <div class="footer-item-right">{{ order.distributionName }}</div>
            </div>
          </div>
          <div class="footer-button">
            <!-- 待接单状态：显示接单按钮 -->
            <div v-if="['0', '1'].includes(order.status)" class="footer-button-item primary"
              @click.stop="takeOrder(order)">
              <div>接单</div>
            </div>

            <!-- 状态为2时显示取货和取消接单按钮 -->
            <template v-if="order.status === '2'">
              <div class="footer-button-item" @click.stop="contactStore(order)">
                <div>联系商家</div>
              </div>
              <div class="footer-button-item" @click.stop="cancelOrder(order)">
                <div>取消接单</div>
              </div>
              <div class="footer-button-item primary" @click.stop="startDelivery(order)">
                <div>取货</div>
              </div>
            </template>

            <!-- 状态为3时显示送达按钮和联系用户 -->
            <template v-if="order.status === '3'">
              <div class="footer-button-item" @click.stop="contactCustomer(order)">
                <div>联系用户</div>
              </div>
              <div class="footer-button-item primary" @click.stop="confirmDelivery(order)">
                <div>送达</div>
              </div>
            </template>
          </div>
        </div>
      </template>

      <!-- 加载更多 -->
      <div v-if="loadingMore" class="loading-container">
        <div class="loading">加载更多...</div>
      </div>
    </scroll-view>
    <!-- 添加拍照和备注弹窗 -->
    <wd-popup v-model="showPhotoDialog" position="center">
      <view class="photo-dialog">
        <view class="dialog-title">
          {{ currentOrderAction === 'pickup' ? '取货凭证' : '送达凭证' }}
        </view>
        <view class="photo-area">
          <view class="photo-list">
            <view v-for="(photo, index) in photoList" :key="index" class="photo-item">
              <image :src="photo.serverUrl || photo.localPath" mode="aspectFill" />
            </view>
            <view class="photo-add" @click="handleTakePhoto" v-if="photoList.length < 3">
              <text class="iconfont icon-camera"></text>
              <text>拍照</text>
            </view>
          </view>
        </view>

        <view class="remarks-area">
          <textarea v-model="remarks" placeholder="请输入备注信息" class="remarks-input" />
        </view>

        <view class="dialog-footer">
          <button @click="showPhotoDialog = false" class="btn-cancel">取消</button>
          <button @click="submitPhotoAndRemarks" class="btn-submit">确定</button>
        </view>
      </view>
    </wd-popup>
  </div>
</template>

<script setup>
import { baseUrl } from '@/utils/config'
// 获取用户数据
import { useLoginStore } from '@/stores/login'
const loginStore = useLoginStore()
import { ref, onMounted, computed } from 'vue'
import { Fetch } from '@/composables/useFetch'
import Return from '@/components/Return.vue'

const capsuleTop = ref(0)
const contentHeight = ref(0)
const activeIndex = ref(0)
const loading = ref(false)
const loadingMore = ref(false)
const refreshing = ref(false)
const orderList = ref([])
const page = ref(1)
const hasMore = ref(true)

// 收入数据
const todayIncome = ref(0)
const totalIncome = ref(0)

const takeoutOrderList = ref([
  { title: '已接单', status: '2', type: 'my' },
  { title: '配送中', status: '3', type: 'my' },
  { title: '已完成', status: '4', type: 'my' }
])
// 状态文本映射
const statusTextMap = {
  '0': '商家待接单',
  '1': '商家已接单',
  '2': '商家出餐-待配送',
  '3': '骑手已取餐-配送中',
  '4': '骑手配送完成-已完成',
  '5': '待评价',
  '6': '取消',
  '7': '退款中',
  '8': '退款完成',
  '9': '订单已取消',
}

// 在现有的状态声明后添加
const showPhotoDialog = ref(false)
const currentOrderAction = ref(null)
const currentOrder = ref(null)
const photoList = ref([])
const remarks = ref('')


// 修改 startDelivery 函数
const startDelivery = async (order) => {
  currentOrder.value = order;
  currentOrderAction.value = 'pickup';
  photoList.value = [];
  remarks.value = '';
  showPhotoDialog.value = true;
}

// 修改 confirmDelivery 函数
const confirmDelivery = async (order) => {
  currentOrder.value = order;
  currentOrderAction.value = 'delivery';
  photoList.value = [];
  remarks.value = '';
  showPhotoDialog.value = true;
}

// 添加拍照功能
const handleTakePhoto = () => {
  uni.chooseImage({
    count: 1,
    sourceType: ['camera'],
    success: async (res) => {
      const tempFilePath = res.tempFilePaths[0];

      // 显示上传中提示
      uni.showLoading({
        title: '上传中...'
      });

      try {
        // 上传图片到服务器
        const uploadRes = await uni.uploadFile({
          url: `${baseUrl}shopping/sysFile/upload`,
          filePath: tempFilePath,
          name: 'file',
          header: {
            'accesstoken': loginStore.token
          }
        });

        const result = JSON.parse(uploadRes.data);
        if (result.code === 200) {
          photoList.value.push({
            localPath: tempFilePath,
            serverUrl: result.data.fileUrl
          });
        } else {
          uni.showToast({
            title: '上传失败',
            icon: 'none'
          });
        }
      } catch (error) {
        console.error('上传失败:', error);
        uni.showToast({
          title: '上传失败',
          icon: 'none'
        });
      } finally {
        uni.hideLoading();
      }
    }
  });
};

// 添加提交凭证和备注的功能
const submitPhotoAndRemarks = async () => {
  if (photoList.value.length === 0) {
    uni.showToast({
      title: '请拍照上传',
      icon: 'none'
    });
    return;
  }

  const photoUrls = photoList.value.map(photo => photo.serverUrl).filter(Boolean);
  if (photoUrls.length < photoList.value.length) {
    uni.showToast({
      title: '部分图片未上传成功',
      icon: 'none'
    });
    return;
  }

  try {
    const apiUrl = currentOrderAction.value === 'pickup'
      ? `shopping/riderOrders/takeMealOrder`
      : `shopping/riderOrders/completeOrder`;

    const result = await Fetch(apiUrl, {
      method: 'POST',
      data: {
        imgUrl: photoUrls.join(','),
        remark: remarks.value,
        orderId: currentOrder.value.orderId
      }
    });

    if (result.data.code === 200) {
      showPhotoDialog.value = false;
      uni.showToast({
        title: currentOrderAction.value === 'pickup' ? '已开始配送' : '配送完成',
        icon: 'success'
      });
      getOrderList(true);
    } else {
      uni.showToast({
        title: result.data.message || '操作失败',
        icon: 'none'
      });
    }
  } catch (error) {
    console.error('操作失败:', error);
    uni.showToast({
      title: '操作失败',
      icon: 'none'
    });
  }
}
// 获取状态文本
const getStatusText = (status) => {
  return statusTextMap[status] || '未知状态'
}
// 计算当前筛选状态
const currentStatus = computed(() => {
  return takeoutOrderList.value[activeIndex.value]?.status || ''
})

// 计算内容区高度
function calcContentHeight() {
  const systemInfo = uni.getSystemInfoSync()
  // #ifdef MP-WEIXIN
  const menuButtonInfo = wx.getMenuButtonBoundingClientRect()
  capsuleTop.value = menuButtonInfo.bottom + 20
  // #endif
  contentHeight.value = systemInfo.windowHeight - capsuleTop.value - (systemInfo.safeAreaInsets?.bottom || 0)
}

// 获取订单列表
const getOrderList = async (isRefresh = false) => {
  if (loading.value && !isRefresh) return

  if (isRefresh) {
    page.value = 1
    hasMore.value = true
  }

  if (!hasMore.value) return

  loading.value = true
  loadingMore.value = !isRefresh

  try {
    // 根据当前标签类型选择不同的接口
    const currentTab = takeoutOrderList.value[activeIndex.value];

    const params = {
      page: page.value,
      limit: 10,
      status: currentStatus.value
    }

    const { status, data } = await Fetch('shopping/riderOrders/findReceivedOrderList', {
      method: 'GET',
      data: params
    })

    console.log(status, data, 'status, data ');

    if (status === 200 && data.code === 200) {
      const newOrders = data.rows || []

      if (isRefresh) {
        orderList.value = newOrders
      } else {
        orderList.value.push(...newOrders)
      }

      hasMore.value = newOrders.length === 10
      page.value++
    } else {
      uni.showToast({
        title: data?.msg || '获取订单失败',
        icon: 'none'
      })
    }
  } catch (error) {
    console.error('获取订单失败:', error)
    uni.showToast({
      title: '网络错误',
      icon: 'none'
    })
  } finally {
    loading.value = false
    loadingMore.value = false
    refreshing.value = false
  }
}

// 获取收入统计
const getIncomeStats = async () => {
  try {
    const { status, data } = await Fetch('/api/delivery/income-stats', {
      method: 'GET'
    })

    if (status === 200 && data.code === 0) {
      todayIncome.value = data.result.todayIncome || 0
      totalIncome.value = data.result.totalIncome || 0
    }
  } catch (error) {
    console.error('获取收入统计失败:', error)
  }
}

// 切换标签
const handleTabChange = (index) => {
  if (activeIndex.value === index) return
  activeIndex.value = index
  getOrderList(true)
}

// 下拉刷新
const onRefresh = async () => {
  refreshing.value = true
  await Promise.all([
    getOrderList(true),
    getIncomeStats()
  ])
}

// 加载更多
const loadMore = () => {
  if (!loading.value && hasMore.value) {
    getOrderList()
  }
}



// 查看订单详情
const viewOrderDetail = (order) => {
  uni.navigateTo({
    url: `/pages/OrderDetail?id=${order.id}`
  })
}

// 联系店家
const contactStore = (order) => {
  if (order.storePhone) {
    uni.makePhoneCall({
      phoneNumber: order.storePhone,
      fail: () => {
        uni.showToast({
          title: '拨打电话失败',
          icon: 'none'
        })
      }
    })
  } else {
    uni.showToast({
      title: '暂无联系方式',
      icon: 'none'
    })
  }
}

// 到达取货点
const arrivePickup = async (order) => {
  try {
    const { status, data } = await Fetch('/api/delivery/arrive-pickup', {
      method: 'POST',
      data: { orderId: order.id }
    })

    if (status === 200 && data.code === 0) {
      uni.showToast({
        title: '已到达取货点',
        icon: 'success'
      })
      // 刷新订单列表
      getOrderList(true)
    } else {
      uni.showToast({
        title: data?.msg || '操作失败',
        icon: 'none'
      })
    }
  } catch (error) {
    console.error('操作失败:', error)
    uni.showToast({
      title: '网络错误',
      icon: 'none'
    })
  }
}

// 完成配送
const completeDelivery = async (order) => {
  try {
    const { status, data } = await Fetch('/api/delivery/complete', {
      method: 'POST',
      data: { orderId: order.id }
    })

    if (status === 200 && data.code === 0) {
      uni.showToast({
        title: '配送完成',
        icon: 'success'
      })
      // 刷新订单列表
      getOrderList(true)
    } else {
      uni.showToast({
        title: data?.msg || '操作失败',
        icon: 'none'
      })
    }
  } catch (error) {
    console.error('操作失败:', error)
    uni.showToast({
      title: '网络错误',
      icon: 'none'
    })
  }
}

// 提现
const handleWithdraw = () => {
  uni.navigateTo({
    url: '/pages/WithdrawCash'
  })
}

onMounted(() => {
  calcContentHeight()
  // 监听屏幕变化（如横竖屏切换）
  uni.onWindowResize && uni.onWindowResize(calcContentHeight)

  // 初始化数据
  getOrderList(true)
  // getIncomeStats()
})
</script>

<style lang="scss" scoped>
.takeout-order {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background: #f5f5f5;

  .takeout-order-header {
    background: #F5F5F5;
    position: relative;
    margin-bottom: 20rpx;
    z-index: 2;

    .takeout-order-header-top {
      color: #191919;
      font-weight: bold;
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 0 20rpx;
      box-sizing: border-box;

      .takeout-order-header-top-item {
        padding: 24rpx;
        box-sizing: border-box;
        width: 344rpx;
        height: 196rpx;
        background: #FFFFFF;
        border-radius: 16rpx 16rpx 16rpx 16rpx;

        .top-title {
          display: flex;
          align-items: center;

          view {
            &:nth-child(2) {
              width: 80rpx;
              height: 42rpx;
              background: #FBE050;
              border-radius: 46rpx 46rpx 46rpx 46rpx;
              color: #292706;
              font-size: 24rpx;
              font-weight: bold;
              line-height: 42rpx;
              text-align: center;
              margin-left: auto;
            }
          }
        }

        .priceStr {
          display: flex;
          align-items: center;
          justify-content: center;
          font-size: 36rpx;
          margin-top: 34rpx;

          view {
            &:nth-child(1) {
              font-size: 32rpx;
            }

            &:nth-child(2) {
              font-size: 38rpx;
            }
          }
        }
      }
    }

    .takeout-order-header-bottom {
      height: 96rpx;
      display: flex;
      align-items: center;
      justify-content: space-between;
      background: white;
      margin-top: 30rpx;

      .takeout-order-header-bottom-item {
        width: 100%;
        height: 100%;
        display: flex;
        align-items: center;
        justify-content: center;

        .item-box {
          font-weight: bold;
          font-size: 28rpx;
          color: #191919;
          line-height: 40rpx;
          text-align: center;
          font-style: normal;
          text-transform: none;
          cursor: pointer;
        }

        .item-box-active {
          position: relative;

          &::after {
            content: '';
            display: block;
            width: 40rpx;
            height: 8rpx;
            background: #F9DC40;
            border-radius: 4rpx 4rpx 4rpx 4rpx;
            position: absolute;
            bottom: -10rpx;
            left: 50%;
            transform: translateX(-50%);
          }
        }
      }
    }
  }

  .takeout-order-content {
    overflow: auto;
    background: #F5F5F5;
    padding: 0 20rpx 50rpx;
    box-sizing: border-box;

    .loading-container,
    .empty-container {
      display: flex;
      justify-content: center;
      align-items: center;
      height: 200rpx;
      background: #F5F5F5;
      border-radius: 20rpx;
      margin-top: 20rpx;
    }

    .loading {
      font-size: 28rpx;
      color: #999999;
    }

    .empty-text {
      font-size: 28rpx;
      color: #999999;
    }

    .takeout-order-content-item {
      width: 710rpx;
      background: #FFFFFF;
      border-radius: 20rpx 20rpx 20rpx 20rpx;
      padding: 24rpx;
      box-sizing: border-box;
      margin-bottom: 20rpx;

      .takeout-order-content-item-header {
        display: flex;
        align-items: center;
        margin-bottom: 32rpx;

        image {
          width: 76rpx;
          height: 76rpx;
          border-radius: 16rpx 16rpx 16rpx 16rpx;
          margin-right: 16rpx;
        }

        .takeout-order-content-item-header-title {
          flex: 1;

          .takeout-order-content-item-header-title-top {
            display: flex;
            align-items: center;

            .store-name {
              font-size: 30rpx;
              color: #000000;
              font-weight: bold;
            }

            .store-name-tag {
              font-weight: 400;
              font-size: 26rpx;
              color: #666666;
              line-height: 36rpx;
              text-align: center;
              font-style: normal;
              text-transform: none;
              margin-left: auto;
            }
          }

          .takeout-order-content-item-header-title-button {
            display: flex;
            color: #A0A0A0;
            font-size: 22rpx;
            margin-top: 10rpx;

            label {
              display: block;
              font-size: 24rpx;
              color: #9B9B9B;
              font-weight: normal;
              margin-right: 24rpx;
            }
          }
        }

      }

      .item-center {
        margin-top: 32rpx;
      }

      .total-priceStr {
        display: flex;
        justify-content: flex-end;
        align-items: center;
        margin-top: 18rpx;
        margin-bottom: 30rpx;

        view {
          font-size: 22rpx;

          &:nth-child(1) {
            font-size: 30rpx;
          }

          &:nth-child(2) {
            font-size: 30rpx;
            margin: 0 5rpx;
          }

          &:nth-child(3) {
            font-size: 36rpx;
            font-weight: bold;
          }
        }
      }

      .takeout-order-content-item-footer {
        margin-top: 30rpx;

        .footer-item {
          display: flex;
          font-size: 26rpx;
          color: #191919;
          margin-bottom: 20rpx;

          .footer-item-left {
            flex: 1;
          }

          .footer-item-right {
            width: 300rpx;
            text-align: right;
          }
        }
      }

      .footer-button {
        display: flex;
        align-items: center;
        justify-content: flex-end;
        margin-top: 30rpx;

        .footer-button-item {
          width: 242rpx;
          height: 72rpx;
          line-height: 72rpx;
          text-align: center;
          color: #333333;
          font-size: 28rpx;
          font-weight: bold;
          border-radius: 14rpx 14rpx 14rpx 14rpx;
          cursor: pointer;

          &:nth-child(1) {
            background: #F5F5F5;
          }

          &:nth-child(2),
          &.primary {
            background: #FBE050;
            margin-left: 30rpx;
          }
        }
      }
    }
  }
}

.info {
  display: flex;
  align-items: center;
  margin-bottom: 20rpx;

  image {
    width: 98rpx;
    height: 98rpx;
    border-radius: 16rpx 16rpx 16rpx 16rpx;
  }

  .info-content {
    flex: 1;
    margin-left: 20rpx;

    .info-content-top {
      display: flex;

      .store-name {
        font-size: 26rpx;
        color: #191919;
        line-height: 36rpx;
        text-align: center;
        font-style: normal;
        text-transform: none;
      }

      .store-name-tag {
        display: flex;
        align-items: center;
        color: #191919;
        margin-left: auto;

        view {
          font-size: 22rpx;

          &:nth-child(1) {
            font-size: 26rpx;
          }

          &:nth-child(2) {
            font-size: 22rpx;
            margin: 0 5rpx;
          }

          &:nth-child(3) {
            font-size: 32rpx;
            font-weight: bold;
          }
        }
      }

    }

    .info-content-button-item-remark {
      font-size: 22rpx;
      color: #999999;
    }

    .info-content-button-item {
      display: flex;
      align-items: center;
      color: #999999;
      font-size: 22rpx;
    }
  }
}

.page-line {
  width: 662rpx;
  height: 1rpx;
  background: #F5F5F5;
}
/* 新增弹窗样式 */
.photo-dialog {
  width: 650rpx;
  border-radius: 20rpx;
  background-color: #fff;
  padding: 30rpx;

  .dialog-title {
    font-size: 32rpx;
    font-weight: bold;
    text-align: center;
    margin-bottom: 30rpx;
  }

  .photo-area {
    margin-bottom: 30rpx;

    .photo-list {
      display: flex;
      flex-wrap: wrap;

      .photo-item {
        width: 180rpx;
        height: 180rpx;
        margin-right: 20rpx;
        margin-bottom: 20rpx;

        image {
          width: 100%;
          height: 100%;
          border-radius: 10rpx;
        }
      }

      .photo-add {
        width: 180rpx;
        height: 180rpx;
        background-color: #f5f5f5;
        border-radius: 10rpx;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        font-size: 24rpx;
        color: #666;

        .iconfont {
          font-size: 48rpx;
          margin-bottom: 10rpx;
        }
      }
    }
  }

  .remarks-area {
    margin-bottom: 30rpx;

    .remarks-input {
      width: 100%;
      height: 150rpx;
      background-color: #f5f5f5;
      border-radius: 10rpx;
      padding: 20rpx;
      box-sizing: border-box;
      font-size: 28rpx;
    }
  }

  .dialog-footer {
    display: flex;
    justify-content: space-between;

    button {
      width: 280rpx;
      height: 80rpx;
      border-radius: 40rpx;
      font-size: 28rpx;
      display: flex;
      align-items: center;
      justify-content: center;
    }

    .btn-cancel {
      background-color: #E0E0E0;
      color: #191919;
    }

    .btn-submit {
      background-color: #F9DC40;
      color: #191919;
      font-weight: bold;
    }
  }
}
</style>
